package it.azienda.managerworkstandard.filtri;

import it.azienda.framework.utilita.Utilita;
import it.azienda.managerworkstandard.modello.BeanLogin;
import java.io.IOException;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class FiltroSessione implements Filter{
    
    /** Creates a new instance of FiltroSessione */
    public FiltroSessione() {
    }
    
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        
        try{
            HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
            String contextPath = httpRequest.getContextPath();
            String servletPath = httpRequest.getServletPath();
            if (!servletPath.equals("/login.jsf")) {
                HttpSession session = httpRequest.getSession();
                BeanLogin operatore = (BeanLogin) session.getAttribute("login");
                if (session.isNew() || operatore.getNome() == null) {
                    ServletContext application = session.getServletContext();
                    application.log("FiltroSessione: Sto filtrando la richiesta a " + contextPath + " - " + servletPath);
                    RequestDispatcher dispatcher = application.getRequestDispatcher("/schermoErrore.jsp");
                    dispatcher.forward(servletRequest, servletResponse);
                    return;
                }
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }catch(Exception ex){
            ex.printStackTrace();
            HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
            HttpSession session = httpRequest.getSession();
            ServletContext application = session.getServletContext();
            httpRequest.setAttribute("errore",ex.toString());
            RequestDispatcher dispatcher = application.getRequestDispatcher("/errore.jsp");
            dispatcher.forward(servletRequest, servletResponse);
        }
    }
    
    public void destroy() {
    }
    
}
